package gncom.qr;

import gncom.qr.facebook.DialogError;
import gncom.qr.facebook.Facebook;
import gncom.qr.facebook.Facebook.DialogListener;
import gncom.qr.facebook.FacebookError;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class StoryWritePage extends Activity {
	
	private EditText storyEdit;
	private SQLiteDatabase mDatabase;
	private Button writeOkBtn, facebookWriteOkBtn;

	private int id;
	private int position;
	
	private final String FACEBOOK_APP_ID = "129244043848555";
	private final int FACEBOOK_AUTH_CODE = 32665;
	
	private Facebook mFacebook;

	// Loading Dialog
	private ProgressDialog mProgressDialog1;
	private ProgressDialog mProgressDialog2;  
	private String mFacebookAccessToken;
	
	private LocationManager locationManager;
	private Location location;
	private String locationProvider;
	private String strLatitude;
	private String strLongitude;
	private String strState;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.story_write_page);
		
		Log.i("story", "StoryWritePage.......");
		
		locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		locationProvider = locationManager.getBestProvider(new Criteria(), true);
		location = locationManager.getLastKnownLocation(locationProvider);

		//1.DB 연결.
		openData();
		
		//2.id 값 받기.
		id = getIntent().getIntExtra("id", 1);
		position = getIntent().getIntExtra("position", -1);
		
		Log.i("qrstory", "id:"+id+" , position:"+position);
		
		storyEdit = (EditText)findViewById(R.id.storyEdit);
		
		mFacebook = new Facebook(FACEBOOK_APP_ID);

		mFacebookAccessToken = getAppPreferences(this, "ACCESS_TOKEN");
		mFacebook.setAccessToken(mFacebookAccessToken);
		
		if (position != -1){
			if(StoryPage.list.get(position).getStory() != null){
				storyEdit.setText(StoryPage.list.get(position).getStory());
			}
		}
		
		writeOkBtn = (Button)findViewById(R.id.writeOkBtn);
		writeOkBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				if(storyEdit.getText().length()==0){
					Toast.makeText(getApplicationContext(), "내용을 입력하세요", 0).show();
					return;
				}
				
				postQR25();
				saveStory(id);	
				Toast.makeText(getApplicationContext(), "QR Story 에 글을 남기셨습니다.\n카테고리 별로 보실 수 있습니다.", 0).show();
			}
		});
		
		facebookWriteOkBtn = (Button)findViewById(R.id.facebookUploadBtn);
		facebookWriteOkBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(storyEdit.getText().length()==0){
					Toast.makeText(getApplicationContext(), "내용을 입력하세요", 0).show();
					return;
				}
				loginFacebook();
				Toast.makeText(getApplicationContext(), "FaceBook 에 글을 남기셨습니다.\n담벼락에서 보실 수 있습니다.", 0).show();
			}
		});
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		locationManager.removeUpdates(locationListener);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		locationManager.removeUpdates(locationListener);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		locationManager.requestLocationUpdates(locationProvider, 3000, 10, locationListener);
	}
	
	private void openData() {
		mDatabase = openOrCreateDatabase("storyInfo", SQLiteDatabase.CREATE_IF_NECESSARY, null);
		Cursor c = mDatabase.rawQuery("select name from sqlite_master where type=? and name=?", new String[] {"table", "qrStory"});
		if (c.getCount() == 0) {
			mDatabase.execSQL("create table qrStory(id integer primary key autoincrement, url text, cdate long, story text);");
		}
	}
	
	protected void saveStory(int id) {
		ContentValues values = new ContentValues();
		values.put("story", storyEdit.getText().toString());
		mDatabase.update("qrStory", values, "id=?", new String[]{id + ""});
	}
  
	private void loginFacebook() {
		if (!"".equals(mFacebookAccessToken) && mFacebookAccessToken != null) {
			mFacebook.setAccessToken(mFacebookAccessToken);
			postFacebook();
		} else {
			mFacebook.authorize2(this, new String[] {"user_photos, email, photo_upload, publish_stream, status_update, share_item, video_upload, create_note, offline_access, read_stream"}, new AuthorizeListener());
		}
	}
	
	private void postQR25() {
		mProgressDialog1 = ProgressDialog.show(this, null, "데이터 업로드 중...", true, false);
		
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				try {
					// QR 관리자 사이트에 업로드
					HttpClient client = new DefaultHttpClient();  
					
					String postURL = "http://mobile.gncom.co.kr:8080/qr25/mobile/pds_write1_ok.jsp";
					HttpPost post = new HttpPost(postURL);
					MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
					
					String uuid = "35"
						+ Build.BOARD.length()%10
						+ Build.BRAND.length()%10
						+ Build.CPU_ABI.length()%10
						+ Build.DEVICE.length()%10
						+ Build.DISPLAY.length()%10
						+ Build.HOST.length()%10
						+ Build.ID.length()%10
						+ Build.MANUFACTURER.length()%10
						+ Build.MODEL.length()%10
						+ Build.PRODUCT.length()%10
						+ Build.TAGS.length()%10
						+ Build.TYPE.length()%10
						+ Build.USER.length()%10;
					
					byte[] photo = bitmapToByteArray(setBase64Decoder(StoryPage.list.get(position).getQr_img()));
					
					reqEntity.addPart("upload", new ByteArrayBody(photo, new Date().getTime()+".png"));
					reqEntity.addPart("uuid", new StringBody(uuid));
					reqEntity.addPart("subject", new StringBody(URLEncoder.encode(storyEdit.getText().toString(), "euc-kr")));
					reqEntity.addPart("content", new StringBody("content"));
					reqEntity.addPart("url", new StringBody(StoryPage.list.get(position).getUrl()));
					reqEntity.addPart("latitude", new StringBody(strLatitude));
					reqEntity.addPart("longitude", new StringBody(strLongitude));
					reqEntity.addPart("myfacebook", new StringBody("1"));
					reqEntity.addPart("qrfacebook", new StringBody("1"));
				
					post.setEntity(reqEntity);
										
					HttpResponse responsePOST = client.execute(post); 
					HttpEntity resEntity = responsePOST.getEntity();

					mHandler1.sendEmptyMessage(100);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					mHandler1.sendEmptyMessage(-100);
				}
			}
		});
		thread.start();		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode==KeyEvent.KEYCODE_BACK) {
			Intent clearTop = new Intent(this, StoryPage.class);
			clearTop.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			//clearTop.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(clearTop);
		}
		return super.onKeyDown(keyCode, event);
	}
	
	
	private void postFacebook() {
		mProgressDialog2 = ProgressDialog.show(this, null, "데이터 업로드 중...", true, false);
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					HttpClient client = new DefaultHttpClient();  
					
					String postURL = "http://mobile.gncom.co.kr:8080/qr25/mobile/pds_write1_ok.jsp";
					HttpPost post = new HttpPost(postURL);
					MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
					
					String uuid = "35"
						+ Build.BOARD.length()%10
						+ Build.BRAND.length()%10
						+ Build.CPU_ABI.length()%10
						+ Build.DEVICE.length()%10
						+ Build.DISPLAY.length()%10
						+ Build.HOST.length()%10
						+ Build.ID.length()%10
						+ Build.MANUFACTURER.length()%10
						+ Build.MODEL.length()%10
						+ Build.PRODUCT.length()%10
						+ Build.TAGS.length()%10
						+ Build.TYPE.length()%10
						+ Build.USER.length()%10;
					
					//스토리페이지 
					
					////////////
					Cursor c = mDatabase.query("qrStory", null, "id=?", new String[]{id+""}, null, null, null);
					c.moveToFirst();
					String qr_img = c.getString(c.getColumnIndex("qrcode"));
					startManagingCursor(c);
					
					byte[] photo = bitmapToByteArray(setBase64Decoder(qr_img));
					//byte[] photo = bitmapToByteArray(setBase64Decoder(StoryPage.list.get(position).getQr_img()));
					
					String upload = new Date().getTime()+".png";
					String subject = storyEdit.getText().toString();
					String url = StoryPage.list.get(position).getUrl();
					String webTitle = StoryPage.list.get(position).getWebTitle();
					String no = "";
					
					reqEntity.addPart("upload", new ByteArrayBody(photo, upload));
					reqEntity.addPart("uuid", new StringBody(uuid));
					reqEntity.addPart("subject", new StringBody(URLEncoder.encode(subject, "euc-kr")));
					reqEntity.addPart("content", new StringBody("content"));
					reqEntity.addPart("url", new StringBody(url));
					reqEntity.addPart("latitude", new StringBody(strLatitude));
					reqEntity.addPart("longitude", new StringBody(strLongitude));
					reqEntity.addPart("myfacebook", new StringBody("0"));
					reqEntity.addPart("qrfacebook", new StringBody("0"));
				
					post.setEntity(reqEntity);
										
					HttpResponse responsePOST = client.execute(post); 
					HttpEntity resEntity = responsePOST.getEntity();
					
					if (resEntity != null) {
						JSONArray arr = new JSONArray((EntityUtils.toString(resEntity)).trim());
						JSONObject obj = arr.getJSONObject(0);
						no = (String)obj.get("no");
					}
					
					String message = setDateFormat(StoryPage.list.get(position).getCdate()) + "\n" + subject;
					String name = "QR Story";
					String description = "2.5 Catch Scanner에서 포스팅";
					
					// 자신의 facebook에 업로드
					Bundle myParams = new Bundle();
					myParams.putString("message", message);
					myParams.putString("picture", "http://mobile.gncom.co.kr:8080/qr25/upload/" + upload);
					myParams.putString("link", "http://mobile.gncom.co.kr:8080/qr25/mobile/pds_view1_qr.jsp?no=" + no);
					myParams.putString("name", name);
					myParams.putString("caption", webTitle);
					myParams.putString("description", description);
					
					mFacebook.request("me/feed", myParams, "POST");
										
					// QR Story의 facebook에 업로드
					
					mFacebook.request("QRstory/feed", myParams, "POST");

					saveStory(id);
					
					mHandler2.sendEmptyMessage(100);
				} catch (Exception e) {
					mHandler2.sendEmptyMessage(-100);
				}
			}
		});
		thread.start();
	}
	
	// Facebook 업로드 데이터 처리
	public static String setDateFormat(long cdate) {
		String textDate = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		textDate = sdf.format(cdate);
		return textDate;
	}
	
	public static byte[] bitmapToByteArray(Bitmap b) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		b.compress(CompressFormat.PNG, 100, out);
		byte[] bytearr = out.toByteArray();
		return bytearr;
	}
	
	public Bitmap setBase64Decoder(String imagePath) {
		byte[] bytePlainOrg = Base64.decode(imagePath, 0);
		ByteArrayInputStream inStream = new ByteArrayInputStream(bytePlainOrg);
		Bitmap bm = BitmapFactory.decodeStream(inStream);
		return bm;
	}
	
	// SharedPreferences 처리
	private void setAppPreferences(Activity context, String key, String value) {
		SharedPreferences pref = context.getSharedPreferences("2.5QR", 0);
		SharedPreferences.Editor prefEditor = pref.edit();
		prefEditor.putString(key, value);
		prefEditor.commit();
	}
	  
	private String getAppPreferences(Activity context, String key) {
		SharedPreferences pref = context.getSharedPreferences("2.5QR", 0);
		String returnValue = pref.getString(key, "");	    
		return returnValue;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	    
		if (resultCode == RESULT_OK) {
			if (requestCode == FACEBOOK_AUTH_CODE) {
				mFacebook.authorizeCallback(requestCode, resultCode, data);
			}
		} else {
			if (requestCode == FACEBOOK_AUTH_CODE) {
				mFacebook.authorizeCallback(requestCode, resultCode, data);
			}
		}
	}
	
	// Facebook 로그인 핸들러
	public class AuthorizeListener implements DialogListener {
		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
		}

		@Override
		public void onComplete(Bundle values) {
			// TODO Auto-generated method stub
			postFacebook();
			
			mFacebookAccessToken = mFacebook.getAccessToken();
			setAppPreferences(StoryWritePage.this, "ACCESS_TOKEN", mFacebookAccessToken); 
		}

		@Override
		public void onError(DialogError e) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onFacebookError(FacebookError e) {
			// TODO Auto-generated method stub
		}
	}
	
	// GPS 핸들러
	LocationListener locationListener = new LocationListener() {
		
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			switch (status) {
			case LocationProvider.OUT_OF_SERVICE:
				strState = "현재 상태 : 범위에서 벗어남";
				break;
			case LocationProvider.TEMPORARILY_UNAVAILABLE:
				strState = "현재 상태 : 일시적 불능";
				break;
			case LocationProvider.AVAILABLE:
				strState = "현재 상태 : 사용가능";
				break;
			default:
				break;
			}
		}
		
		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			strState = "현재 상태 : 서비스 사용 가능";
		}
		
		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			strState = "현재 상태 : 서비스 사용 불가";
		}
		
		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			strState = "현재 상태 : 서비스 상태 변경";
			
			strLatitude = location.getLatitude() + "";
			strLongitude = location.getLongitude() + "";
		}
	};
	
	// Facebook 업로드 핸들러
	Handler mHandler1 = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 100) {
				mProgressDialog1.dismiss();
				Toast.makeText(StoryWritePage.this, "QR Site 업로드에 성공하였습니다.", Toast.LENGTH_LONG).show();
				
				finish();
				startActivity(new Intent(getApplicationContext(), StoryPage.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

			} else if (msg.what == -100) {
				mProgressDialog1.dismiss();
				Toast.makeText(StoryWritePage.this, "네트워크 연결에  실패하였습니다.", Toast.LENGTH_LONG).show();
			}
		}
	};
	
	// QR WebSite 업로드 핸들러
	Handler mHandler2 = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 100) {
				mProgressDialog2.dismiss();
				Toast.makeText(StoryWritePage.this, "Facebook 업로드에 성공하였습니다.", Toast.LENGTH_LONG).show();
				
				finish();
				startActivity(new Intent(getApplicationContext(), StoryPage.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

			} else if (msg.what == -100) {
				mProgressDialog2.dismiss();
				Toast.makeText(StoryWritePage.this, "네트워크 연결에  실패하였습니다.", Toast.LENGTH_LONG).show();
			}
		}
	};
}